import AES from 'crypto-js/aes'
import { enc, mode, pad } from 'crypto-js'
const _key = enc.Utf8.parse('bbtoolslovesyou.')
const _iv = enc.Utf8.parse('cWl5dWUtMjAxOQ==')
const actionPerfix = 'https://dei2.com/a/'
export default {
  methods: {
    $encrypt (message) {
      if (!message || !message.trim()) return ''
      let s = ''
      if (typeof message == 'string') {
        s = message
      } else if (typeof message == 'object') {
        s = enc.Utf8.parse(message)
      }
      let encrypted = AES.encrypt(s, _key, {
        iv: _iv,
        mode: mode.CBC,
        pad: pad.Pkcs7
      })
      return encrypted.ciphertext.toString(enc.Base64)
    },
    $decrypt (message) {
      if (!message || !message.trim()) return ''
      let encryptHexStr = enc.Hex.parse(message)
      let s = enc.Base64.stringify(encryptHexStr)
      let decrypt = AES.decrypt(message, _key, {
        iv: _iv,
        mode: mode.CBC,
        pad: pad.Pkcs7
      })
      let decrypted = decrypt.toString(enc.Utf8)
      return decrypted.toString()
    },
    $urlToJson (str) {
      if (!str || (str.indexOf(actionPerfix) < 0)) return {
        action: '',
        data: {}
      }
      let s = str.split(actionPerfix)[1]
      s = decodeURIComponent(s)
      let action = s.split(':')[0]
      let out = {}
      let p = s.split(':')[1].split('&')
      for (let i = 0; i < p.length; i++) {
        out[p[i].split('=')[0]] = p[i].split('=')[1]
      }
      return {
        action,
        data: out
      }
    },
    async $getIPAddress () {
      // 获取 ip http://pv.sohu.com/cityjson?ie=utf-8
      console.log('=======', require.main)
      return ''
      // var interfaces = require('os').networkInterfaces();
      // for (var devName in interfaces) {
      //   var iface = interfaces[devName];
      //   for (var i = 0; i < iface.length; i++) {
      //     var alias = iface[i];
      //     if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
      //       return alias.address;
      //     }
      //   }
      // }
    }
  }
}